import numpy as np
import matplotlib.pyplot as plt
from sklearn import manifold, datasets, decomposition
from sklearn.preprocessing import StandardScaler

# 加载 6 类数字的数据集
digits = datasets.load_digits(n_class=6)
X = digits.data
y = digits.target

# 标准化数据
X = StandardScaler().fit_transform(X)
n_samples, n_features = X.shape
n_neighbors = 30

# 绘制降维后的数据
def plot_embedding(X, y, title=None):
    x_min, x_max = np.min(X, 0), np.max(X, 0)
    X = (X - x_min) / (x_max - x_min)

    plt.figure(figsize=(10, 10))
    for i in range(X.shape[0]):
        plt.text(X[i, 0], X[i, 1], str(y[i]),
                 color=plt.cm.Set1(y[i] / 10.),
                 fontdict={'weight': 'bold', 'size': 9})
    plt.xticks([]), plt.yticks([])
    if title is not None:
        plt.title(title, fontsize=16)

# 展示部分手写数字图像
n_img_per_row = 20
img = np.zeros((10 * n_img_per_row, 10 * n_img_per_row))
for i in range(n_img_per_row):
    ix = 10 * i + 1
    for j in range(n_img_per_row):
        iy = 10 * j + 1
        img[ix:ix + 8, iy:iy + 8] = digits.images[i * n_img_per_row + j]

plt.figure(figsize=(8, 8))
plt.imshow(img, cmap=plt.cm.binary)
plt.xticks([])
plt.yticks([])
plt.title('A selection from the 64-dimensional digits dataset', fontsize=14)

# PCA 降维
print("Computing PCA projection...")
X_pca = decomposition.PCA(n_components=2).fit_transform(X)
plot_embedding(X_pca, y, "PCA projection of the digits dataset")

# t-SNE 嵌入降维
print("Computing t-SNE embedding...")
tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)
X_tsne = tsne.fit_transform(X)
plot_embedding(X_tsne, y, "t-SNE embedding of the digits dataset")

plt.show()
